package priv.wjh.study.juc.impl;

import sun.misc.Unsafe;

import java.util.concurrent.locks.LockSupport;

/**
 * <h1>AQS学习，实现独占模式</h1>
 *
 * @author wangjunhao
 * @see java.util.concurrent.locks.AbstractQueuedSynchronizer
 * <p>目标，可以基于此类实现和{@link java.util.concurrent.locks.ReentrantLock}相同的功能，不包括conndition</p>
 **/
public abstract class MyAQSOne {
    /** waitStatus value to indicate thread has cancelled. */
    static final int CANCELLED =  1;
    /** waitStatus value to indicate successor's thread needs unparking. */
    static final int SIGNAL    = -1;

    /**
     * <h2>线程等待队列节点</h2>
     */
    private static class Node {
        Node prev;
        Node next;
        // 节点所属线程
        Thread thread;

        /** waitStatus value to indicate thread is waiting on condition. */
        // 节点状态, 需设置为volatile，因为下一个节点监听上一个节点的状态，保证修改可以被下个节点读到。
        volatile int waitStatus;

        public Node() {
        }

        public Node(Thread thread) {
            this.thread = thread;
        }

        /**
         * <h2>Cas 设置节点状态</h2>
         * @param expect 期待节点状态值
         * @param update 设置状态节点值
         * @return 是否设置成功
         */
        boolean compareAndSetStatus(int expect, int update) {
            return UNSAFE.compareAndSwapInt(this, WAIT_STATUS_OFFSET, expect, update);
        }

        // 节点状态地址偏移量, 具体位置为：实例地址+偏移量
        private static final long WAIT_STATUS_OFFSET;

        static {

            try {
                WAIT_STATUS_OFFSET = UNSAFE.objectFieldOffset(Node.class.getDeclaredField("waitStatus"));
            } catch (Exception ex) {
                throw new Error(ex);
            }
        }

    }

    /**
     * <h2>线程等待队列</h2>
     * <p>FIFO 队列</p>
     */
    private static class Queue {
        volatile Node head;
        volatile Node tail;

        /**
         * <h2>添加节点入队</h2>
         * @param node 节点
         * @return 节点
         */
        Node enq(Node node) {
            while (true) {
                Node t = tail;
                // 检查队列尾部是不是为空，即队列待进行初始化
                if (t == null) {
                    // 初始化队列 头部和尾部指向一样的节点
                    if (compareAndSetHead(new Node())) {
                        tail = head;
                    }
                } else {
                    // 入队
                    if (compareAndSetTail(t, node)) {
                        // 因为尾部已经被修改为当前节点，
                        // 所以其他线程无法访问到t，所以可以直接赋值
                        // 同理node节点也是一样
                        node.prev = t;
                        t.next = node;
                        return t;
                    }
                }
            }
        }

        /**
         * <h2>当前线程入队</h2>
         * @return 返回线程节点
         */
        Node addWaiter() {
            Node node = new Node(Thread.currentThread());
            Node t = tail;
            if (t != tail) {
                // 设置当前节点为尾节点，设置失败则进入enq函数进行入队操作
                if (compareAndSetTail(t, node)) {
                    node.prev = t;
                    t.next = node;
                    return t;
                }
            }
            enq(node);
            return node;
        }

        boolean compareAndSetHead(Node update) {
            return UNSAFE.compareAndSwapObject(this, HEAD_OFFSET, null, update);
        }

        boolean compareAndSetTail(Node expect, Node update) {
            return UNSAFE.compareAndSwapObject(this, TAIL_OFFSET, expect, update);
        }

        private static final long HEAD_OFFSET;
        private static final long TAIL_OFFSET;

        static {
            try {
                HEAD_OFFSET = UNSAFE.objectFieldOffset(Queue.class.getDeclaredField("head"));
                TAIL_OFFSET = UNSAFE.objectFieldOffset(Queue.class.getDeclaredField("tail"));
            } catch (Exception ex) {
                throw new Error(ex);
            }
        }
    }

    private volatile int state;
    private final Queue queue;

    public MyAQSOne(int state) {
        this.state = state;
        queue = new Queue();
    }

    /**
     * <h2>获取凭证</h2>
     * @param c 凭证数量
     * @return 获取成功返回true，获取失败返回false
     */
    abstract boolean tryAcquire(int c);

    /**
     * <h2>释放凭证</h2>
     * @param c 凭证数量
     * @return 释放成功返回true，释放失败返回false
     */
    abstract boolean tryRelease(int c);

    public boolean tryAcquireNanos(int c, long nanosTimeout) throws InterruptedException {
        if (Thread.interrupted()){
            throw new InterruptedException();
        }
        return tryAcquire(c) || doAcquireNanos(c, nanosTimeout);
    }

    /**
     * <h2>获取凭证</h2>
     * <p>
     *     先把当前节点入队，然后自旋，当前驱节点为头部时，尝试获取凭证。
     *     获取凭证成功，设置当前节点为队列头部。
     *     获取凭证失败，先检测是否以及超过等待时间，超过则返回获取失败
     *     然后再检测线程是否需要中断
     * </p>
     * @param c 获取凭证数量
     * @param nanosTimeout 等待时间
     * @throws InterruptedException
     * @return true 代表获取成功，false代表获取失败
     */
    private boolean doAcquireNanos(int c, long nanosTimeout) throws InterruptedException {
       if (nanosTimeout <= 0L){
           throw new IllegalArgumentException();
       }
       Node node = queue.addWaiter();
       long expired = System.nanoTime() + nanosTimeout;
       boolean failed = true;
        try {
            while (true){
                Node p = node.prev;
                // 检测前驱节点是否为头部，如果为头部则尝试获取凭证
                if (p == queue.head && tryAcquire(c)){
                    queue.compareAndSetHead(node);
                    p.next = null;
                    p.thread = null;
                    failed = false;
                    return true;
                }
                nanosTimeout = expired - System.nanoTime();
                if (nanosTimeout <= 0L){
                    return false;
                }
                // 检测当前线程是否需要中断
                if (shouldParkAfterFailedAcquire(p, node) && nanosTimeout > 1000L){
                    LockSupport.parkNanos(this, nanosTimeout);
                }
                if (Thread.interrupted()){
                    throw new InterruptedException();
                }
            }
        } finally {
            if (failed){
                cancelAcquire(node);
            }
        }
    }
    /**
     * <h2>判断当前线程是否需要暂定</h2>
     * <p>
     *     前驱节点的状态是需要通知，则代表需要暂停,
     *     前驱节点状态为已取消，则略过已取消的节点,
     *     前驱节点状态为其他，修改前驱节点为待通知。
     * </p>
     * @param p
     * @param node
     **/
    private boolean shouldParkAfterFailedAcquire(Node p, Node node) {
        int ws = p.waitStatus;
        // 前驱节点为需要通知
        if (ws == SIGNAL){
            return true;
        }
        if (ws > 0){
            // 略过已取消的前驱节点
            do {
                // 在遍历时就修改节点的前驱，因为在释放节点时，
                // 有可能会从后往前查找第一个待通知的节点，
                // 这样可以提高从后往前查找第一个待通知的节点的效率
                node.prev = p = p.prev;
            }while (p.waitStatus > 0);
            p.next = node;
        }else {
            // 修改前驱节点状态为signal, 代表前驱节点之后有等待的节点
            p.compareAndSetStatus(ws, SIGNAL);
        }
        return false;
    }

    /**
     * <h2>取消节点等待</h2>
     * <p>把当前节点的状态修改为取消状态，并释放当前节点</p>
     * @param node
     */
    private void cancelAcquire(Node node) {
        // 修改节点状态
        node.waitStatus = CANCELLED;
        // 获取节点前驱的第一个没有取消的节点
        Node pred = node.prev;
        while (pred.waitStatus > 0){
            pred = pred.prev;
        }
        pred.next = node.next;
        if (pred == queue.head){

        }

    }

    private void unparkSuccessor(Node node){
        int ws = node.waitStatus;
        if (ws < 0){
            node.compareAndSetStatus(ws, 0);
        }
        Node next = node.next;
        if (next == null || next.waitStatus > 0){
            next = null;
            for (Node t = queue.tail; t != null && t != queue.head; t = t.prev){
                if (t.waitStatus <= 0){
                    next = t;
                }
            }
        }
        if (next != null){
            LockSupport.unpark(next.thread);
        }

    }

    public boolean release(int c){
        if (tryRelease(c)) {
            Node h = queue.head;
            if (h != null && h.waitStatus != 0) {
                unparkSuccessor(h);
            }
            return true;
        }
        return false;
    }

    void setState(int state){
        this.state = state;
    }

    int getState(){
        return this.state;
    }



    boolean compareAndSetState(int expect, int update){
        return UNSAFE.compareAndSwapInt(this, STATE_OFFSET, expect, update);
    }

    private static final Unsafe UNSAFE = Unsafe.getUnsafe();

    private static final long STATE_OFFSET;

    static {
        try {
            STATE_OFFSET = UNSAFE.objectFieldOffset(MyAQSOne.class.getDeclaredField("state"));
        } catch (Exception ex) {
            throw new Error(ex);
        }
    }

}
